package com.example.pei.ithinklearnt.present;

import android.content.Intent;
import android.widget.Toast;

import com.example.pei.ithinklearnt.AppApplication;
import com.example.pei.ithinklearnt.bean.AlumniCircle;
import com.example.pei.ithinklearnt.bean.UserInfo;
import com.example.pei.ithinklearnt.listener.compressPicturesListener;
import com.example.pei.ithinklearnt.task.compressPicturesTask;
import com.example.pei.ithinklearnt.view.interfaces.addDynamicInterface;

import java.util.List;

import cn.bmob.v3.datatype.BmobFile;
import cn.bmob.v3.exception.BmobException;
import cn.bmob.v3.listener.SaveListener;
import cn.bmob.v3.listener.UpdateListener;
import cn.bmob.v3.listener.UploadBatchListener;

import static android.app.Activity.RESULT_OK;
import static com.example.pei.ithinklearnt.utils.MyUtils.isAllSpace;

/**
 * Created by Pei on 2017/12/10.
 */

public class addDynamicPresentImp implements addDynamicPresent{

    private addDynamicInterface mAddDynamicInterface;
    AlumniCircle alumniCircle;

    private String objectId;

    public addDynamicPresentImp (addDynamicInterface addDynamicInterface1){
        this.mAddDynamicInterface=addDynamicInterface1;
    }



    @Override
    public void textChanged() {
        if(isAllSpace(mAddDynamicInterface.getContent())&&mAddDynamicInterface.getPhotoList().size()==0){
            mAddDynamicInterface.setAddButtonStype(false);     //没有输入内容
        }else {
            mAddDynamicInterface.setAddButtonStype(true);
        }
        int s=150-mAddDynamicInterface.getContent().length();
        mAddDynamicInterface.setTextViewNum(s+"");
    }

    @Override
    public void sendDynamic() {

        mAddDynamicInterface.setAddButtonClickable(false);//设置不可点击
        mAddDynamicInterface.setSweetAlertDialog(true);   //开始加载
        UserInfo currentUser= AppApplication.getCurrentUser();
        alumniCircle=new AlumniCircle();

        alumniCircle.setContent(mAddDynamicInterface.getContent());

        alumniCircle.setSender(currentUser);


        if(mAddDynamicInterface.getPhotoList().size()==0){
            alumniCircle.setPhotoNumber(0);
        }else{
            alumniCircle.setPhotoNumber(-1);   //-1代表不是正常的数值，后面上传成功则不会为-1
        }


        //创建一条记录
        alumniCircle.save(new SaveListener<String>() {
            @Override
            public void done(final String objectid, BmobException e) {
                if(e==null){
                    objectId=objectid;
                    int photoNum=mAddDynamicInterface.getPhotoList().size();
                    //如果添加动态成功，则开始添加图片信息
                    final String[] filePaths = new String[photoNum];
                    for(int i=0;i<photoNum;i++){
                        filePaths[i]=mAddDynamicInterface.getPhotoList().get(i);
                    }
                    if(photoNum!=0){ //有图片需要上传
                        compressPictures(filePaths);
                    }else{
                        //没有图片需要上传则可以直接结束活动
                        Intent intent = new Intent();
                        intent.putExtra("data_return", "success");
                        mAddDynamicInterface.getActivity().setResult(RESULT_OK, intent);

                        //progress取消显示
                        mAddDynamicInterface.setSweetAlertDialog(false);
                        mAddDynamicInterface.getActivity().finish();

                    }

                }else {
                    Toast.makeText(mAddDynamicInterface.getActivity(),"sorry...创建失败了",Toast.LENGTH_LONG).show();
                    //progress取消显示
                    mAddDynamicInterface.setSweetAlertDialog(false);
                    mAddDynamicInterface.setAddButtonClickable(true);
                }
            }
        });
    }

    private static int comPressNum;
    private String[] compressPictures(final String[] paths){

        final String[] newPath=new String[paths.length];
        for (int i=0;i<paths.length;i++){
            newPath[i]=mAddDynamicInterface.getActivity().getExternalCacheDir()+"/dynamic"+i+".jpg";

            new compressPicturesTask(new compressPicturesListener() {
                @Override public void onProgress(int progress) {}
                @Override public void onFailed() {}

                @Override
                public void onSuccess() {
                    comPressNum++;
                    if(comPressNum==paths.length){
                        comPressNum=0;


                        BmobFile.uploadBatch(newPath, new UploadBatchListener() {
                            @Override
                            public void onSuccess(List<BmobFile> list, List<String> urls) {

                                if(urls.size()==newPath.length){//如果数量相等，则代表文件全部上传完成

                                    alumniCircle.setPhoto(urls);
                                    alumniCircle.setPhotoNumber(urls.size());
                                    alumniCircle.update(objectId, new UpdateListener() {
                                        @Override
                                        public void done(BmobException e) {
                                            if(e==null){
                                                //发送成功，可以结束活动
                                                Intent intent = new Intent();
                                                intent.putExtra("data_return", "success");
                                                mAddDynamicInterface.getActivity().setResult(RESULT_OK, intent);
                                                //移除progress
                                                mAddDynamicInterface.setSweetAlertDialog(false);
                                                mAddDynamicInterface.getActivity().finish();
                                            }else{
                                                Toast.makeText(mAddDynamicInterface.getActivity(),"图片更新失败"+e.getMessage(),Toast.LENGTH_LONG).show();
                                                mAddDynamicInterface.setAddButtonClickable(true);
                                            }
                                        }
                                    });
                                }
                            }
                            @Override
                            public void onProgress(int i, int i1, int i2, int i3) {
                                //1、curIndex--表示当前第几个文件正在上传
                                //2、curPercent--表示当前上传文件的进度值（百分比）
                                //3、total--表示总的上传文件数
                                //4、totalPercent--表示总的上传进度（百分比）
                            }
                            @Override
                            public void onError(int i, String s) {
                                Toast.makeText(mAddDynamicInterface.getActivity(),"图片上传失败："+s,Toast.LENGTH_LONG).show();
                            }
                        });
                    }
                }

            }).execute(paths[i],newPath[i],"10240");
        }
        return newPath;
    }





}
